package com.batata.continuing.service.user;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.batata.continuing.dao.user.UserDao;
import com.batata.continuing.pojo.base.ResultData;
import com.batata.continuing.pojo.user.LoginUserInfo;
import com.batata.continuing.pojo.user.UserInfo;
import com.batata.continuing.service.common.RedisService;
import com.batata.continuing.utils.JwtUtil;
import com.batata.continuing.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import static com.batata.continuing.service.common.ResultCommon.resultDataCommon;


/**
 * 登陆逻辑处理中心
 */
@Service
@Transactional
public class UserLoginService extends ServiceImpl<UserDao, UserInfo> {


    @Autowired
    private RedisService redisService;

    @SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 登陆验证
     */
    public ResultData<?> userLoginVerify(String loginName, String loginPassword) {
        QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("login_name", loginName);
        queryWrapper.eq("login_password", loginPassword);
        Long userCount = this.baseMapper.selectCount(queryWrapper);
        if (userCount < 1) {
            return resultDataCommon(500, "无此用户", false);
        }
        // 查询用户基础信息
        LoginUserInfo loginInfo = this.baseMapper.getLoginInfo(loginName);
        // 生成token
        loginInfo.setToken(JwtUtil.sign(loginInfo.getId().toString()));
        // 将用户信息存储在reids中方便后期取用
//        addLoginInfoToRedis(loginInfo);  todo  这样写redis出问题了接口也就不行了

        return resultDataCommon(200, "登录成功", true, loginInfo);
    }

    /**
     * 将登录信息存储在redis中
     *
     * @param loginUserInfo 用户登录信息
     */
    public void addLoginInfoToRedis(LoginUserInfo loginUserInfo) {
        // 判断是否存在
        if (redisService.exists(loginUserInfo.getId().toString())) {
            // 将老的删除
            redisService.remove(loginUserInfo.getId().toString());
        }

        redisService.setCacheObject(loginUserInfo.getId().toString(), loginUserInfo);
        redisService.expire(loginUserInfo.getId().toString(), JwtUtil.getExpireTime());

    }


}
